"""
工作流模板管理 API 路由
"""
import json
from fastapi import APIRouter, Depends, HTTPException, Query
from sqlalchemy.orm import Session
from typing import Optional

from database import get_db
from schemas.workflow_template_schema import (
    WorkflowTemplateCreate,
    WorkflowTemplateUpdate,
    WorkflowTemplateResponse,
    WorkflowTemplateDetailResponse,
    WorkflowTemplateListResponse,
    VersionHistoryResponse,
    VersionDiffResponse,
    RollbackRequest
)
from services.workflow_template_service import WorkflowTemplateService

router = APIRouter(prefix="/api/workflow-templates", tags=["工作流模板管理"])


# ============ 模板 CRUD 接口 ============

@router.post("", response_model=WorkflowTemplateDetailResponse, summary="创建工作流模板")
def create_template(
    template_create: WorkflowTemplateCreate,
    db: Session = Depends(get_db)
):
    """
    创建工作流模板

    - **name**: 模板名称(必填)
    - **description**: 模板描述(可选)
    - **workflow_definition**: 工作流定义(必填)
    """
    success, error_msg, template = WorkflowTemplateService.create_template(db, template_create)

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return WorkflowTemplateDetailResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        workflow_definition=json.loads(template.workflow_definition),
        version=template.version,
        parent_version_id=template.parent_version_id,
        change_log=template.change_log,
        status=template.status,
        created_at=template.created_at,
        updated_at=template.updated_at,
        created_by=template.created_by
    )


@router.get("", response_model=WorkflowTemplateListResponse, summary="查询模板列表")
def get_template_list(
    page: int = Query(1, ge=1, description="页码"),
    page_size: int = Query(20, ge=1, le=100, description="每页数量"),
    name: Optional[str] = Query(None, description="模板名称(模糊查询)"),
    status: Optional[str] = Query(None, description="模板状态"),
    sort_by: str = Query("created_at", description="排序字段(name/created_at/updated_at)"),
    order: str = Query("desc", description="排序方向(asc/desc)"),
    db: Session = Depends(get_db)
):
    """
    查询模板列表

    支持分页、筛选、排序
    注意：每个模板名称只返回最新版本
    """
    total, templates = WorkflowTemplateService.list_templates(
        db, page, page_size, name, status, sort_by, order
    )

    items = [
        WorkflowTemplateResponse(
            id=t.id,
            name=t.name,
            description=t.description,
            version=t.version,
            status=t.status,
            created_at=t.created_at,
            updated_at=t.updated_at,
            created_by=t.created_by
        )
        for t in templates
    ]

    return WorkflowTemplateListResponse(
        total=total,
        page=page,
        page_size=page_size,
        items=items
    )


@router.get("/{template_id}", response_model=WorkflowTemplateDetailResponse, summary="查询模板详情")
def get_template_detail(
    template_id: int,
    db: Session = Depends(get_db)
):
    """
    查询模板详情
    """
    template = WorkflowTemplateService.get_template(db, template_id)

    if not template:
        raise HTTPException(status_code=404, detail="模板不存在")

    return WorkflowTemplateDetailResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        workflow_definition=json.loads(template.workflow_definition),
        version=template.version,
        parent_version_id=template.parent_version_id,
        change_log=template.change_log,
        status=template.status,
        created_at=template.created_at,
        updated_at=template.updated_at,
        created_by=template.created_by
    )


@router.put("/{template_id}", response_model=WorkflowTemplateDetailResponse, summary="更新模板（创建新版本）")
def update_template(
    template_id: int,
    template_update: WorkflowTemplateUpdate,
    db: Session = Depends(get_db)
):
    """
    更新模板（创建新版本）

    注意：此操作会创建新版本，不会修改原版本
    """
    success, error_msg, template = WorkflowTemplateService.update_template(
        db, template_id, template_update
    )

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return WorkflowTemplateDetailResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        workflow_definition=json.loads(template.workflow_definition),
        version=template.version,
        parent_version_id=template.parent_version_id,
        change_log=template.change_log,
        status=template.status,
        created_at=template.created_at,
        updated_at=template.updated_at,
        created_by=template.created_by
    )


@router.delete("/{template_id}", summary="删除模板")
def delete_template(
    template_id: int,
    db: Session = Depends(get_db)
):
    """
    删除模板(软删除)

    注意：允许删除有关联实例的模板，数据保留供追溯
    """
    success, error_msg = WorkflowTemplateService.delete_template(db, template_id)

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return {"message": error_msg if error_msg else "模板删除成功"}


# ============ 版本管理接口 ============

@router.get("/{template_id}/versions", response_model=VersionHistoryResponse, summary="查询版本历史")
def get_version_history(
    template_id: int,
    db: Session = Depends(get_db)
):
    """
    查询模板的版本历史
    """
    versions = WorkflowTemplateService.get_version_history(db, template_id)

    if not versions:
        raise HTTPException(status_code=404, detail="模板不存在")

    return VersionHistoryResponse(versions=versions)


@router.get("/{template_id}/versions/{version}", response_model=WorkflowTemplateDetailResponse, summary="查询指定版本")
def get_specific_version(
    template_id: int,
    version: int,
    db: Session = Depends(get_db)
):
    """
    查询模板的指定版本
    """
    # 先获取当前模板，以得到模板名称
    current_template = WorkflowTemplateService.get_template(db, template_id)
    if not current_template:
        raise HTTPException(status_code=404, detail="模板不存在")

    # 根据名称和版本号查询
    template = WorkflowTemplateService.get_template_by_name_and_version(
        db, current_template.name, version
    )

    if not template:
        raise HTTPException(status_code=404, detail=f"版本 {version} 不存在")

    return WorkflowTemplateDetailResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        workflow_definition=json.loads(template.workflow_definition),
        version=template.version,
        parent_version_id=template.parent_version_id,
        change_log=template.change_log,
        status=template.status,
        created_at=template.created_at,
        updated_at=template.updated_at,
        created_by=template.created_by
    )


@router.get("/{template_id}/diff", response_model=VersionDiffResponse, summary="版本对比")
def get_version_diff(
    template_id: int,
    version1: int = Query(..., description="版本号1"),
    version2: int = Query(..., description="版本号2"),
    db: Session = Depends(get_db)
):
    """
    对比两个版本的差异
    """
    success, error_msg, diff_data = WorkflowTemplateService.get_version_diff(
        db, template_id, version1, version2
    )

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return VersionDiffResponse(**diff_data)


@router.post("/{template_id}/rollback", response_model=WorkflowTemplateDetailResponse, summary="回滚到指定版本")
def rollback_to_version(
    template_id: int,
    rollback_request: RollbackRequest,
    db: Session = Depends(get_db)
):
    """
    回滚到指定版本

    注意：此操作会创建新版本，内容来自目标版本
    """
    success, error_msg, template = WorkflowTemplateService.rollback_to_version(
        db, template_id, rollback_request.target_version
    )

    if not success:
        raise HTTPException(status_code=400, detail=error_msg)

    return WorkflowTemplateDetailResponse(
        id=template.id,
        name=template.name,
        description=template.description,
        workflow_definition=json.loads(template.workflow_definition),
        version=template.version,
        parent_version_id=template.parent_version_id,
        change_log=template.change_log,
        status=template.status,
        created_at=template.created_at,
        updated_at=template.updated_at,
        created_by=template.created_by
    )
